﻿using Micro.SMSGatWay.Core.Model.Req.APIModel;
using Micro.SMSGatWay.Core.Model.Resp.ApiModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ARC.API.ExternalInterface.CurrencyInterface;
using ARC.API.ExternalInterface.Models;
using Micro.Core.FrameWork.Cache;
using Micro.SMSGatWay.Core.Entity;
using Micro.SMSGatWay.Core.Model;
using Micro.SMSGatWay.Core.Repository.SmsSendHistory;
using Micro.SMSGatWay.Core.Repository.SmsSignInfo;
using Micro.SMSGatWay.Core.Repository.SmsTemplateInfo;
using Microsoft.EntityFrameworkCore;

namespace Micro.SMSGatWay.Core.Service
{
    public class SmsApiService : SmsService, ISmsApiService
    {
        private readonly ISmsSignInfoRepository _smsSignInfoRepository;
        private readonly ISmsTemplateInfoRepository _smsTemplateInfoRepository;
        private readonly ISmsSendHistoryRepository _sendHistoryRepository;
        private readonly ICache _cache;
        private readonly ICurrencyInterfaceSdkSmsClient _currencyInterfaceSdkSmsClient;
        public SmsApiService(SmsAppConfig smsAppConfig, ISmsSignInfoRepository smsSignInfoRepository, ISmsTemplateInfoRepository smsTemplateInfoRepository, ISmsSendHistoryRepository sendHistoryRepository, ICache cache, ICurrencyInterfaceSdkSmsClient currencyInterfaceSdkSmsClient) : base(smsAppConfig)
        {
            _smsSignInfoRepository = smsSignInfoRepository;
            _smsTemplateInfoRepository = smsTemplateInfoRepository;
            _sendHistoryRepository = sendHistoryRepository;
            _cache = cache;
            _currencyInterfaceSdkSmsClient = currencyInterfaceSdkSmsClient;
        }

        public async Task<RespSmsApiResponse> SendSms(ReqSmsSend reqSmsAdd)
        {

            var templatesCache = await GetTemplateCache(reqSmsAdd.GroupId);

            var smsTemplateInfo =
                templatesCache.FirstOrDefault(s => s.ServiceProviderType.Equals((int)reqSmsAdd.ProviderType));

            if (smsTemplateInfo == null)
                return new RespSmsApiResponse() { Code = Status.Error, Msg = "未找到该模板" };

            var signInfoCache = await GetSignCache(smsTemplateInfo.GroupId);

            var signInfo =
                signInfoCache.FirstOrDefault(s => s.ServiceProviderType.Equals((int)reqSmsAdd.ProviderType));

            if (signInfo == null)
                return new RespSmsApiResponse() { Code = Status.Error, Msg = "未找到该签名" };
            ;

            SmsSendHistory smsSendHistory = new SmsSendHistory()
            {
                CampaignId = reqSmsAdd.CampaignId,
                InitTemplateContent = BuildOldTemplate(signInfo, smsTemplateInfo, reqSmsAdd),
                Phone = reqSmsAdd.Phone,
                ServiceProviderType = (int)reqSmsAdd.ProviderType,
            };

            if (reqSmsAdd.ProviderType == ProviderType.ALiYun)//阿里云
            {
                var sdkResponse = _currencyInterfaceSdkSmsClient.SendAliYunSimpleSms(_smsAppConfig.AccessKeyId,
                      _smsAppConfig.AccessKeySecret, reqSmsAdd.Phone, signInfo.SignName, smsTemplateInfo.TemplateCode,
                      JsonSerializer.Serialize(TransForALiYunParams(reqSmsAdd)));


                if (sdkResponse.Code != Status.Success)
                {
                    smsSendHistory.Status = 0;
                    return new RespSmsApiResponse() { Code = sdkResponse.Code, Msg = sdkResponse.Msg };
                }
                smsSendHistory.Status = 1;

                await SaveChangesSendLogs(smsSendHistory);

                return new RespSmsApiResponse() { Code = sdkResponse.Code, Msg = sdkResponse.Msg };
            }
            else if (reqSmsAdd.ProviderType == ProviderType.YunP)//云片
            {
                var sdkResponse = _currencyInterfaceSdkSmsClient.SendYunPianSimpleSms(_smsAppConfig.YunPAppId,
                    reqSmsAdd.Phone, smsTemplateInfo.TemplateCode, TransForYunPParams(reqSmsAdd));
                if (sdkResponse.Code != Status.Success)
                {
                    return new RespSmsApiResponse() { Code = sdkResponse.Code, Msg = "未找到该模板" };
                }

                return new RespSmsApiResponse() { Code = sdkResponse.Code, Msg = sdkResponse.Msg };
            }
            return new RespSmsApiResponse() { Code = Status.ParamenterIsNull, Msg = "没有此服务商" };
        }
        /// <summary>
        /// 短信模板读取redis
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        private async Task<List<SmsTemplateInfo>> GetTemplateCache(string groupId)
        {
            var cache = _cache.Get(groupId);

            if (cache == null)
            {
                var templates = await _smsTemplateInfoRepository.Get(s => s.GroupId.Equals(groupId)).ToListAsync();
                _cache.Set(groupId, templates);

                return templates;
            }
            var model = JsonSerializer.Deserialize<List<SmsTemplateInfo>>(cache);

            return model;
        }
        /// <summary>
        /// 短信签名读取Redis
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        private async Task<List<SmsSignInfo>> GetSignCache(string groupId)
        {
            var cache = _cache.Get(groupId);

            if (cache == null)
            {
                var smsSignInfos = await _smsSignInfoRepository.Get(s => s.GroupId.Equals(groupId)).ToListAsync();
                _cache.Set(groupId, smsSignInfos);

                return smsSignInfos;
            }

            return JsonSerializer.Deserialize<List<SmsSignInfo>>(cache);
        }
        /// <summary>
        /// 保存发送日志
        /// </summary>
        /// <param name="smsSendHistory"></param>
        /// <returns></returns>
        private async Task SaveChangesSendLogs(SmsSendHistory smsSendHistory)
        {
            await _sendHistoryRepository.AddAsync(smsSendHistory);

            await _sendHistoryRepository.SaveChangesAsync();
        }
    }
}
